package com.example.distributesession.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

public class JwtUtil {

    private static String secret = "test@!";

    /**
     * 创建JWT
     */
    public static String createJwt(Map<String, String> claimMap) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 3);
        JWTCreator.Builder builder = JWT.create();
        claimMap.forEach(builder::withClaim);
        return builder.withExpiresAt(calendar.getTime()).sign(Algorithm.HMAC256(secret));
    }

    /**
     * 验证JWT
     */
    public static boolean verifyJWT(String token) {
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
        try {
            jwtVerifier.verify(token);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 解析JWT
     */
    public static String verifyJWT(String token, String key) {
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
        try {
            DecodedJWT verify = jwtVerifier.verify(token);
            return verify.getClaim(key).asString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}